package com.siddy.bbs.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.siddy.bbs.R;

public class SlidingMenuListFragment extends ListFragment {

	public static interface Callbacks {
		public void onMenuItemSelected(int resId);
	}

	private static final MenuItem[] MENUS = new MenuItem[] {
			new MenuItem(R.string.tab_top10, R.drawable.sliding_menu_top10),
			new MenuItem(R.string.tab_recommend, R.drawable.sliding_menu_board),
			new MenuItem(R.string.tab_favorite, R.drawable.sliding_menu_favorite),
			new MenuItem(R.string.tab_board, R.drawable.sliding_menu_board),
			new MenuItem(R.string.tab_setting, R.drawable.sliding_menu_settings) };

	private Callbacks mCallbacks;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.list, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		SampleAdapter adapter = new SampleAdapter(getActivity(), MENUS);
		setListAdapter(adapter);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException("Activity must implement fragment's callbacks.");
		}
		mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mCallbacks = null;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		if (mCallbacks != null)
			mCallbacks.onMenuItemSelected(MENUS[position].tag);
	}

	private static class MenuItem {
		public int tag;
		public int iconRes;

		public MenuItem(int tag, int iconRes) {
			this.tag = tag;
			this.iconRes = iconRes;
		}
	}

	public class SampleAdapter extends ArrayAdapter<MenuItem> {

		public SampleAdapter(Context context, MenuItem[] data) {
			super(context, 0, data);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null);
			}
			ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon);
			icon.setImageResource(getItem(position).iconRes);
			TextView title = (TextView) convertView.findViewById(R.id.row_title);
			title.setText(getItem(position).tag);

			return convertView;
		}

	}
}
